package com.bsh.serviceImpl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsh.api.ApiUtils;
import com.bsh.api.Exception.ApiException;
import com.bsh.mybatis.model.Account;
import com.bsh.mybatis.model.MobileVerifyCode;
import com.bsh.mybatis.model.User;
import com.bsh.mybatis.model.UserVerifyInfo;
import com.bsh.repository.DaoAccount;
import com.bsh.repository.DaoUser;
import com.bsh.repository.DaoUserVerifyInfo;
import com.bsh.service.ApiLoginService;
import com.bsh.service.SmsService;
import com.bsh.service.UserVerifyService;
import com.bsh.utils.ApiMessage;
import com.bsh.utils.Constants;
import com.bsh.utils.DesUtils;
import com.bsh.utils.HttpClientUtils;

@Service
public class ApiLoginServiceImpl implements ApiLoginService {

	private static Logger log = LoggerFactory
			.getLogger(ApiLoginServiceImpl.class);

	@Autowired
	private DaoUser userDao;
	@Autowired
	private DaoUserVerifyInfo veriDao;
	@Autowired
	private DaoAccount daoAcc;
	@Autowired
	SmsService servSms;
	@Autowired
	UserVerifyService userVerifyService;

	/**
	 * api登录
	 */
	@Override
	public Map<String, Object> apiLogin(JSONObject dto) throws ApiException {
		if (ApiUtils.objIsEmpty(dto.getString("password"))) {
			throw new ApiException(Constants.REQ_PARAM_MISS, "请输入密码");
		}
		if (ApiUtils.objIsEmpty(dto.getString("userName"))) {
			throw new ApiException(Constants.REQ_PARAM_MISS, "请输入用户名");
		}
		// 密码加密校验
		DesUtils des = new DesUtils();
		String enPassword = des.encryptPassword(dto.getString("password"));
		User user=new User();		
		try {
			user = userDao.getLoginUser(dto.getString("userName"), enPassword);
		} catch (Exception e1) {
			throw new ApiException("400", "您的手机号可能关联多个用户, 请联系客服。");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		if (ApiUtils.objIsNotEmpty(user)) {
			if (user.getIsEffect() == null || user.getIsEffect() <= 0) {
				throw new ApiException("400", "用户未检验, 联系客服解冻");
			}
			try {
				user.setDeviceNum(dto.getString("deviceNum"));
				user.setDeviceOem(dto.getString("deviceOem"));
				user.setDeviceOs(dto.getString("deviceOs"));
				user.setDeviceSize(dto.getString("deviceSize"));
				user.setDeviceType(dto.getString("deviceType"));
				user.setModifyTime(new Date());
				userDao.updateByPrimaryKey(user);
			} catch (Exception e) {
				log.error("保存登录信息失败" + user.getName());
			}
			Map<String, Object> userInfo = new HashMap<String, Object>();
			userInfo.put("id", user.getId());
			userInfo.put("userName", user.getName());
			userInfo.put("mobile", user.getMobile());
			// 推荐人存在判断0719
			if (user.getPid() != null && user.getPid() > 0) {
				User userPname = userDao.getUser(user.getPid());
				if (ApiUtils.objIsNotEmpty(userPname)) {
					userInfo.put("pname", userPname.getId());
				} else {
					userInfo.put("pname", user.getPid());
				}
			} else {
				userInfo.put("pname", user.getPid());
			}
			userInfo.put("level", user.getLevel());
			int isMerchantValue = -1; // 默认-1 ：不是商家
			if (user.getIsMerchant() != null) {
				isMerchantValue = user.getIsMerchant().intValue();
			}
			userInfo.put("createTime", user.getCreateTime());
			userInfo.put("isEffect", user.getIsEffect());
			userInfo.put("email", user.getEmail());
			userInfo.put("ip", null);
			userInfo.put("partnerLevel", 0);
			userInfo.put("isMerchant", isMerchantValue);
			userInfo.put("sex", user.getSex()); // 性别: M=男 male， F=女 female
			// 添加是否实名认证内容
			boolean isVerify = veriDao.getVerifyInfo(user.getId()).size() > 0;
			String idcard = "";
			if (isVerify) {
				idcard = (String) veriDao.getVerifyInfo(user.getId()).get(0)
						.get("idcard");
			}
			userInfo.put("isVerify", isVerify);
			userInfo.put("idcard", idcard);
			// 添加头像
			String headImg = "";
			if (ApiUtils.objIsNotEmpty(user.getHeadImg())) {
				headImg = dto.getString("picUrl")+user.getHeadImg();
			}
			userInfo.put("headImg", headImg);

			data.put("userInfo", userInfo);
			data.put("token",
					ApiUtils.getToken(user.getName(), user.getPassword()));

			Account accInfo = daoAcc.getUserAccount(user.getId());
			if (ApiUtils.objIsEmpty(accInfo)) {
				daoAcc.initUserAcount(user.getId(), dto.getString("ip"));
			}
			Map<String, Object> accInfos = new HashMap<String, Object>();
			accInfos.put("money", accInfo.getMoney());
			accInfos.put("cloudMoney", accInfo.getCloudMoney());
			accInfos.put("cashbackMoney", "");
			accInfos.put("cashbackTime", "");
			data.put("accountInfo", accInfos);

		} else {
			throw new ApiException(Constants.REQ_PARAM_ERROR, "用户名或密码错误");
		}

		return data;

	}
    /**
     * 实名认证
     */
	@Override
	public ApiMessage apiAuthNameIdentify(JSONObject dto)throws ApiException {
		ApiMessage msg = new ApiMessage();
		if (ApiUtils.objIsEmpty(dto.getString("userName"))) {
			throw new ApiException(Constants.REQ_PARAM_MISS, "缺少用户名");
		}
		if (ApiUtils.objIsEmpty(dto.getString("token"))) {
			throw new ApiException(Constants.REQ_PARAM_MISS, "缺少token");
		}

		// 查询出对应的用户对象
		User user = userDao.selectByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException(Constants.REQ_PARAM_ERROR, "用户或密码错误");
			
		}
		String cacheVerify=String.valueOf(SmsServiceImpl.cache.Get(dto.getString("smsVerifyCode")+"securitySetting"));
		
		String dBverify ="" ;

		if (ApiUtils.objIsEmpty(cacheVerify)
				|| cacheVerify.equals("null")) {
			MobileVerifyCode record=new MobileVerifyCode();
			record.setMobile(user.getMobile());
			record.setType("securitySetting");
			dBverify = servSms.findCodeByMobile(record);
		}

		if (ApiUtils.objIsEmpty(dto.getString("smsVerifyCode"))) {
			throw new ApiException(Constants.REQ_PARAM_MISS, "请输入验证码");
		} else if (!dto.getString("smsVerifyCode").equals(cacheVerify)&&!dto.getString("smsVerifyCode").equals(dBverify)) {
			log.error("实名认证验证码类型"+"securitySetting"+"用户名:"+dto.getString("userName")+"缓存:"+cacheVerify+"数据库:"+dBverify+"输入验证码:"+dto.getString("smsVerifyCode"));
			throw new ApiException(Constants.REQ_PARAM_ERROR, "验证码错误");
		}

		if (ApiUtils.objIsEmpty(dto.getString("identifyName"))) {
			throw new ApiException(Constants.REQ_PARAM_MISS, "缺少认证姓名");
		} else if (!ApiUtils.isName(dto.getString("identifyName"))) {
			throw new ApiException(Constants.REQ_PARAM_ERROR, "姓名非法");
		}
		if (ApiUtils.objIsEmpty(dto.getString("identifyNumber"))) {
			throw new ApiException(Constants.REQ_PARAM_MISS, "缺少持卡人身份证号");
		} 
		String url = Constants.ID_URL + "?appkey=" + Constants.ID_API_KEY
				+ "&name=" + dto.getString("identifyName") + "&cardno="
				+ dto.getString("identifyNumber");
		try {
			String result = HttpClientUtils.executeGet(url);
			System.out.println(result);
			JSONObject jsonObj = (JSONObject) JSON.parse(result);
			if (ApiUtils.objIsEmpty(jsonObj)) {
				throw new ApiException(Constants.SYS_ERROR, "请求失败");
			} else if (jsonObj.getInteger("isok") == 1) {
				UserVerifyInfo uvi = new UserVerifyInfo();
				uvi.setName(dto.getString("identifyName"));
				uvi.setIdcard(dto.getString("identifyNumber"));
				JSONObject data = (JSONObject) jsonObj.get("data");
				uvi.setSex(ApiUtils.objIsEmpty(data.getString("sex")) ? "M"
						: data.getString("sex"));
				uvi.setIp(dto.getString("ip"));
				uvi.setUserid(user.getId());
				uvi.setCreateTime(new Date());
				if (jsonObj.getInteger("code") == 1) {
					uvi.setIsPass((short) 1);
					msg = new ApiMessage(Constants.REQ_SUCCESS, "认证成功");
					user.setRealName(dto.getString("identifyName"));
					user.setSex(ApiUtils.objIsEmpty(data.getString("sex")) ? "M": data.getString("sex"));
					user.setModifyTime(new Date());
					userDao.updateByPrimaryKey(user);
				} else if (jsonObj.getInteger("code") == 2) {
					uvi.setIsPass((short) 0);
					msg = new ApiMessage(Constants.REQ_PARAM_ERROR, "认证失败,身份不匹配");
				} else if (jsonObj.getInteger("code") == 3) {
					uvi.setIsPass((short) 0);
					msg = new ApiMessage(Constants.REQ_PARAM_ERROR, "认证失败,无此身份证号码");
				}
				userVerifyService.saveUserVerifyInfo(uvi);
				
			} else if (jsonObj.getInteger("isok") == 0) {
				if (jsonObj.getInteger("code") == 11) {
					msg = new ApiMessage(Constants.SYS_ERROR, "认证失败,参数不正确");
				} else if (jsonObj.getInteger("code") == 12) {
					msg = new ApiMessage(Constants.SYS_ERROR, "认证失败,商户余额不足");
				} else if (jsonObj.getInteger("code") == 13) {
					msg = new ApiMessage(Constants.SYS_ERROR, "认证失败,appkey不存在");
				} else if (jsonObj.getInteger("code") == 14) {
					msg = new ApiMessage(Constants.SYS_ERROR, "认证失败,IP被拒绝");
				} else if (jsonObj.getInteger("code") == 20) {
					msg = new ApiMessage(Constants.SYS_ERROR, "认证失败,身份证中心维护中");
				}
			}
		} catch (Exception e) {
			throw new ApiException(Constants.SYS_ERROR, "认证失败,请求异常");
			
		}
		
		return msg;
	}

}
